<?php

namespace addons\filewatcher;

use app\common\library\Menu;
use think\Addons;
use think\Request;

/**
 * 文件修改自动刷新插件
 */
class Filewatcher extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {

        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {

        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {

        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {

        return true;
    }

    /**
     * 注册命令
     */
    public function appInit()
    {
        if (request()->isCli()) {
            \think\Console::addDefaultCommands([
                'addons\filewatcher\library\Filewatcher'
            ]);
        }
    }

    /**
     * 配置
     * @param $params
     */
    public function configInit(&$params)
    {
        $config = $this->getConfig();
        $params['filewatcher'] = [
            'port' => $config['port'],
        ];
    }

    /**
     * 视图替换
     * @param $content
     */
    public function viewFilter(&$content)
    {
        $config = $this->getConfig();
        $request = Request::instance();
        $module = strtolower($request->module());
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $url = addon_url("filewatcher/index/client", [], false, true);

        //后台内页无需添加
        if ($module === 'admin' && $controller !== 'index') {
            return;
        }
        $dispatch = $request->dispatch();
        //判断是否插件模块
        $module = $module ?: (($dispatch['method'][0] ?? '') === '\think\addons\Route' ? 'addons' : '');
        $modules = explode(',', $config['modules']);
        if (!in_array($module, $modules)) {
            return;
        }
        $html = "<script type=\"text/javascript\" src=\"{$url}\"></script>";
        $content = str_replace("</body>", $html, $content);
    }

}
